//
//  OAuthViewController.swift
//  SinaWebo
//
//  Created by mis on 16/3/18.
//  Copyright © 2016年 mis. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {
    

    
    let webView = UIWebView()

    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func save() {
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value='15757104578', document.getElementById('passwd').value='13524576801li'")
    }
    
    private func loadWebView() {
        let url = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let request = NSURLRequest(URL: NSURL(string: url)!)
        webView.loadRequest(request)
        print(url)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "save")
        loadWebView()
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
}

extension OAuthViewController: UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
        if urlString.hasPrefix("https://api.weibo.com") {
            return true
        }
        if !urlString.hasPrefix(redirect_uri) {
            return false
        }
        guard let query = request.URL?.query else{
            return false
        }
        let codeStr = "code="
        let code = query.substringFromIndex(codeStr.endIndex)
        print(code)
        UserAccountViewModel().loadAccessToken(code) { (error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus(appErroTip)
                return
            }
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                NSNotificationCenter.defaultCenter().postNotificationName(AppSwitchRootViewControler, object: "Welcome")
            })
        }
        return false
    }
    
}
